package com.learn.base.aspect;

import cn.hutool.core.date.SystemClock;
import com.learn.base.annotation.SysLog;
import com.learn.base.sys.service.SysLogService;
import com.learn.base.utils.IpHelperUtil;
import com.learn.base.utils.JsonUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * @author : Yu.Tan
 * @date : 2023/1/17 16:11
 * @desc : 系统操作日志
 */
@Aspect
@Component
public class SysLogAspect {

    @Autowired
    private SysLogService sysLogService;

    @Around("@annotation(sysLog)")
    public Object around(ProceedingJoinPoint joinPoint, SysLog sysLog) throws Throwable {
        //开始时间
        long beginTime = SystemClock.now();
        //执行方法
        Object result = joinPoint.proceed();
        //结束时间
        long endTime = SystemClock.now();
        //执行时长 毫秒
        long time = endTime - beginTime;

        com.learn.base.sys.entity.SysLog sysLogEntity = new com.learn.base.sys.entity.SysLog();
        //请求的方法名称
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        String method = className + "." + methodName + "()";

        if (sysLog != null) {
            //注解上的描述
            sysLogEntity.setOperation(sysLog.value());
        }
        //请求的方法名称
        sysLogEntity.setMethod(method);
        //请求的参数
        Object[] args = joinPoint.getArgs();
        String params = JsonUtil.toJsonString(args);
        sysLogEntity.setParams(params);
        //设置IP地址
        sysLogEntity.setIp(IpHelperUtil.getIpAddress());
        //操作用户
        String userName = "系统";
        sysLogEntity.setUsername(userName);
        sysLogEntity.setTime(time);
        sysLogEntity.setCreateDate(new Date());
        sysLogService.save(sysLogEntity);
        return result;
    }

}
